<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-alert
          title="只允许为第三级分类设置相关参数"
          type="warning"
          show-icon
          :closable="false"
        >
        </el-alert>
        <el-row class="selectClass">
          <el-col>
            <span>选择商品分类：</span>
              <el-cascader
              v-model="selectdIds"
              :options="goodsClassList"
              :props="props"
              change-on-select
              clearable
              expand-trigger="hover"
              @change="handleChange"></el-cascader>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="dialogVisible = true" :disabled="isBtnDisable">添加参数</el-button>
            <el-table
              :data="manyDataList"
              border
              >
              <el-table-column
                type="expand">
                <template slot-scope="scope">
                  <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="deleteTag(scope.row,index)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column
                type="index"
                width="180">
              </el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
               >
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" class="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" class="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态参数" name="only">
            <el-button @click="dialogVisible = true" :disabled="isBtnDisable">添加参数</el-button>
            <el-table
              :data="onlyDataList"
              border
            >
              <el-table-column
                type="expand">
                <template slot-scope="scope">
                  <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="deleteTag(scope.row, index)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column
                type="index"
                width="180">
              </el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
              >
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" class="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" class="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        :title="'添加'+getproperty"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose">
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="rules">
          <el-form-item :label="getproperty" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="addParam">确 定</el-button>
  </span>
      </el-dialog>
      <el-dialog
        :title="'修改'+getproperty"
        :visible.sync="editDialogVisible"
        width="50%"
        :before-close="handleEditClose">
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editRules">
          <el-form-item :label="getproperty" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="handleEditClose">取 消</el-button>
    <el-button type="primary" @click="editParam">确 定</el-button>
  </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      manyDataList: [],
      rules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      editRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: ''
      },
      onlyDataList: [],
      selectdIds: [],
      goodsClassList: [],
      activeName: 'many',
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      }
    }
  },
  methods: {
    async deleteTag(row, index) {
      const temVals = row.attr_vals
      temVals.splice(index, 1)
      const strVals = temVals.join(',')
      const { data: res } = await this.$http.put(`categories/${this.thirdclassId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: strVals
      })
      if (res.meta.status !== 200) {
        return this.$message.error('删除元素失败')
      }
      this.$message.success('删除元素成功')
      row.attr_vals = temVals
    },
    async getGoodsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.goodsClassList = res.data
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(row) {
      const param = row.inputValue.trim()
      if (param.length !== 0) {
        const temVals = row.attr_vals
        temVals.push(param)
        const strVals = temVals.join(',')
        const { data: res } = await this.$http.put(`categories/${this.thirdclassId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: strVals
        })
        if (res.meta.status !== 200) {
          this.$message.error('添加元素失败')
          return
        } else {
          this.$message.success('添加元素成功')
          row.attr_vals = temVals
        }
      }
      row.inputValue = ''
      row.inputVisible = false
    },
    handleChange() {
      this.getParamsData()
    },
    async getParamsData() {
      if (this.selectdIds.length !== 3) {
        this.selectdIds = []
        this.manyDataList = []
        this.onlyDataList = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.thirdclassId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyDataList = res.data
      } else if (this.activeName === 'only') {
        this.onlyDataList = res.data
      }
    },
    handleClick() {
      this.getParamsData()
    },
    handleClose() {
      this.$refs.addFormRef.resetFields()
      this.dialogVisible = false
    },
    handleEditClose() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    addParam() {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) {
          return
        }
        const { data: res } = await this.$http.post(`categories/${this.thirdclassId}/attributes`, { attr_sel: this.activeName, attr_name: this.addForm.attr_name })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.dialogVisible = false
        this.getParamsData()
      })
    },
    editParam() {
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) {
          return
        }
        const { data: res } = await this.$http.put(`categories/${this.thirdclassId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) {
          return this.$message.error('更改参数失败')
        }
        this.getParamsData()
        this.$message.success('更改参数成功')
        this.editDialogVisible = false
      })
    },
    async editDialog(attrId) {
      const { data: res } = await this.$http.get(`categories/${this.thirdclassId}/attributes/${attrId}`, { attr_sel: this.activeName, attr_name: this.editForm.attr_name })
      if (res.meta.status !== 200) {
        this.$message.error('获取参数信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    async removeParam(attrId) {
      const result = await this.$confirm('此操作将删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.success('已取消删除操作')
      }
      const { data: res } = await this.$http.delete(`categories/${this.thirdclassId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('已删除参数')
      this.getParamsData()
    }
  },
  computed: {
    isBtnDisable() {
      if (this.selectdIds.length !== 3) {
        return true
      }
      return false
    },
    thirdclassId() {
      if (this.selectdIds.length === 3) {
        return this.selectdIds[2]
      }
      return null
    },
    getproperty() {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态属性'
    }
  },
  created() {
    this.getGoodsList()
  }
}
</script>

<style scoped>
  .selectClass {
    margin:15px 0;
  }
  .el-tag {
    margin: 10px;
  }
  .input-new-tag {
    width: 120px;
  }

</style>
